package com.wing.oauth2.details.userdetails.user;

import com.wing.common.enums.AuthMethodEnum;
import com.wing.common.utils.JsonResult;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserAuthVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 系统用户体系业务类
 *
 * @author
 */
@Service("sysUserDetailsService")
@Slf4j
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService {

    private final UserClient userClient;

    /**
     * 用户名或手机号加载用户信息
     *
     * @param username 用户名或手机号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        JsonResult<UserAuthVO> userResult = userClient.findUserByUsername(username);
        if(!JsonResult.hasData(userResult)){
            throw new UsernameNotFoundException("");
        }
        return this.buildUserDetails(userResult.getData(), AuthMethodEnum.USERNAME);
    }

    public UserDetails loadUserByMobile(long phone) {
        JsonResult<UserAuthVO> userResult = userClient.findUserByPhone(phone);
        if (!JsonResult.hasData(userResult)) {
            throw new UsernameNotFoundException("手机号错误");
        }
        return this.buildUserDetails(userResult.getData(), AuthMethodEnum.MOBILE);
    }

    public UserDetails loadUserByOpenId(String openId) {
        JsonResult<UserAuthVO> userResult = userClient.findUserByOpenId(openId);
        if (!JsonResult.hasData(userResult)) {
            throw new UsernameNotFoundException("openId错误");
        }
        return this.buildUserDetails(userResult.getData(), AuthMethodEnum.OPENID);
    }


    /**
     * 构建用户详细信息
     *
     * @param user 系统用户
     * @return 用户详细对象
     */
    private UserDetails buildUserDetails(UserAuthVO user, AuthMethodEnum methodEnum) {

        SysUserDetails userDetails = new SysUserDetails(user);
        userDetails.setAuthMethod(methodEnum.getValue());

        if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }

        return userDetails;
    }

}
